package com.thread.sync.sync02;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Volatile不具备原子性
 */
public class VolatileNoAtomic extends Thread {
    /**
     * AtomicInteger可以实现原子性,类似的还有AtomicBoolean,AtomicIntegerArray
     */
    private static AtomicInteger count = new AtomicInteger(0);

    public void addCount() {
        for (int i = 0; i < 1000; i++) {
            count.incrementAndGet();// ++
            //count.addAndGet(1);// ++,可指定任意数字
        }
        System.out.println(count);
    }

    public void run() {
        addCount();
    }

    public static void main(String[] args) {
        //创建10个对象,如果最后结果是10000,则具有原子性
        VolatileNoAtomic[] va = new VolatileNoAtomic[10];
        for (int i = 0; i < 10; i++) {
            new VolatileNoAtomic().start();
        }
    }

}
